package com.xieyx.licenseplate;


import android.content.Context;
import android.content.DialogInterface;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

/**
 * 汽车车牌
 */
public class LicensePlateTextView extends LinearLayout{

    private static final int[] VIEW_IDS = new int[]{
            R.id.item_code_iv1, R.id.item_code_iv2, R.id.item_code_iv3,
            R.id.item_code_iv4, R.id.item_code_iv5, R.id.item_code_iv6,
            R.id.item_code_iv7, R.id.item_code_iv8 };

    private TextView[] TextViews;

    private String inputContent;

    private StringBuffer stringBuffer = new StringBuffer();

    private OnFrameTouchListener mTouchListener = new OnFrameTouchListener();

    private boolean isUpdateView = false;//是否更新view内容

    private int updateViewPosition;

    private static int ITEM_VIEW_COUNT = 7;

    private Context mContext;

    private LicensePlateDialog dialog;

    private LinearLayout llPlate;//车牌输入框

    private TextView tvNoPlate;//无牌

    private boolean isNoPlate = false;//是否无牌

    private LicensePlateDialogListener licensePlateDialogListener;


    public void setLicensePlateDialogListener(LicensePlateDialogListener listener){
        licensePlateDialogListener = listener;
    }

    public LicensePlateTextView(Context context) {
        super(context);
        mContext = context;
        init(context);
    }

    public LicensePlateTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        init(context);
    }

    private void init(Context context){
        View view = LayoutInflater.from(context).inflate(R.layout.layout_license_plate_frame,null);
        int textsLength = VIEW_IDS.length;
        TextViews = new TextView[8];
        llPlate = view.findViewById(R.id.ll_plate);
        tvNoPlate = view.findViewById(R.id.tv_noPlate);
        for (int i = 0; i < textsLength; i++) {
            //textview放进数组中，方便修改操作
            TextViews[i] = view.findViewById(VIEW_IDS[i]);
            TextViews[i].setOnTouchListener(mTouchListener);
        }
        if(dialog == null){
            dialog = new LicensePlateDialog(mContext);
        }
        addView(view);

        dialog.setOnKeyClickListener(new LicensePlateDialog.OnKeyClickListener() {
            @Override
            public void onKeyClick(String key) {
                tvNoPlate.setText("");
                int start = stringBuffer.length();
                if (key.equalsIgnoreCase("删")) {
                    if (start > 0) {
                        isUpdateView = false;
                        updateViewPosition = 0;
                        stringBuffer.delete(start - 1, start);
                        setEditText();
                    }
                    return;
                } else if(key.equalsIgnoreCase("无牌")){
                    llPlate.setVisibility(GONE);
                    tvNoPlate.setVisibility(VISIBLE);
                    tvNoPlate.setText(key);
                    isNoPlate = true;
                }else {
                    isNoPlate = false;
                    tvNoPlate.setText("");
                    llPlate.setVisibility(VISIBLE);
                    tvNoPlate.setVisibility(GONE);
                    if (isUpdateView) {
                        stringBuffer.replace(updateViewPosition, updateViewPosition + 1, key);

                    } else {
                        if (stringBuffer.length() < ITEM_VIEW_COUNT) {
                            stringBuffer.append(key);
                        }
                    }
                    setEditText();
                }
            }
        });
        tvNoPlate.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if(!dialog.isShowing()){
                    if(licensePlateDialogListener != null){
                        licensePlateDialogListener.onLicensePlateDialogShow();
                    }
                    dialog.showDiaLog();
                    dialog.switchProvince();
                }
            }
        });
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                if(licensePlateDialogListener != null){
                    licensePlateDialogListener.onLicensePlateDialogHide();
                }
            }
        });
    }

    /**
     * 设置输入内容 
     */
    private void setEditText(){
        inputContent = stringBuffer.toString();
        if (isUpdateView) {
            for (int i = 0; i < stringBuffer.length(); i++) {
                TextViews[i].setText(String.valueOf(inputContent.charAt(i)));
            }

            if(stringBuffer.length() > 0){
                setTextViewsBackground(stringBuffer.length()-1);
            }
            setTextViewsBackground(updateViewPosition);

            if(updateViewPosition+1 < ITEM_VIEW_COUNT){

                if(!TextUtils.isEmpty(stringBuffer.substring(updateViewPosition,updateViewPosition+1))){
                    updateViewPosition ++;
                }else{
                    isUpdateView = false;
                }
            }else{
                isUpdateView = false;
            }
            if(updateViewPosition == 0){
                dialog.switchProvince();
            }else{
                dialog.switchNum();
            }
        } else {
            for (int i = 0; i < TextViews.length; i++) {
                TextViews[i].setText("");
            }
            for (int i = 0; i < stringBuffer.length(); i++) {
                TextViews[i].setText(String.valueOf(inputContent.charAt(i)));
            }

            if(stringBuffer.length() > 0){
                setTextViewsBackground(stringBuffer.length()-1);
            }
            if(stringBuffer.length() == 0){
                dialog.switchProvince();
            }else{
                dialog.switchNum();
            }
        }
    }

    /**
     * 设置8位车牌
     */
    public void setPlateTo8(){
        ITEM_VIEW_COUNT = 8;
        TextViews[7].setVisibility(View.VISIBLE);
    }

    /**
     * 设置7位车牌
     */
    public void setPlateTo7(){
        ITEM_VIEW_COUNT = 7;
        TextViews[7].setVisibility(View.GONE);
    }

    /**
     * 获取车牌
     */
    public String getPlateText(){
        String plate = "";

        if(isNoPlate){
            plate = tvNoPlate.getText().toString();
            return plate;
        }

        for(int i = 0;i < ITEM_VIEW_COUNT;i++){
            plate = plate+TextViews[i].getText().toString();
        }

        if( plate.length() != ITEM_VIEW_COUNT){
            plate = "";
        }
        return plate;
    }

    /**
     * 设置车牌
     */
    public void setPlateText(String plate){

        if(TextUtils.isEmpty(plate) || plate.contains("无")){
            isNoPlate = true;
            llPlate.setVisibility(GONE);
            tvNoPlate.setVisibility(VISIBLE);
            tvNoPlate.setText("无牌");
            return;
        }

        if(plate.length() > 8){
            return;
        }

        try {
            for(int i = 0;i<plate.length();i++){
                TextViews[i].setText(plate.substring(i,i+1));
            }
            stringBuffer.append(plate);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 清空内容
     */
    public void cleatText(){
        stringBuffer.setLength(0);
        for(int i = 0;i<TextViews.length;i++){
            TextViews[i].setText("");
        }
    }

    /**
     * 设置不可编辑
     */
    public void setPlateEnable(){
        tvNoPlate.setEnabled(false);
        for(int i = 0;i<TextViews.length;i++){
            TextViews[i].setEnabled(false);
        }
    }

    /**
     * 设置背景
     * @param position
     */
    private void setTextViewsBackground(int position) {
        for (int i = 0; i < 8; i++) {
            TextViews[i].setBackgroundResource(R.drawable.license_plate_mid_view_bg);
        }
        TextViews[position].setBackgroundResource(R.drawable.license_plate_mid_view_blue);
    }


    /**
     * 显示输入框的TouchListener
     */
    private class OnFrameTouchListener implements OnTouchListener {

        @Override
        public boolean onTouch(View view, MotionEvent event) {
            if (view instanceof TextView) {
                if(!dialog.isShowing()){
                    if(licensePlateDialogListener != null){
                        licensePlateDialogListener.onLicensePlateDialogShow();
                    }
                    dialog.showDiaLog();
                }

                TextView tv = (TextView) view;
                tv.setFocusable(true);
                String tvString = (String) tv.getText();
                int viewId = tv.getId();

                //点击时有值，执行修改
                if (!TextUtils.isEmpty(tvString)) {
                    for (int i = 0; i < stringBuffer.length(); i++) {
                        if (viewId == VIEW_IDS[i]) {
                            updateViewPosition = i;
                            if (i == 0) {
                                dialog.switchProvince();
                            } else {
                                dialog.switchNum();
                            }
                            isUpdateView = true;
                            setTextViewsBackground(i);
                        }
                    }
                }else{//点击光标在末尾
                    isUpdateView = false;
                    if(stringBuffer.length() == 0){
                        dialog.switchProvince();
                    }else{
                        dialog.switchNum();
                    }
                }
            }
            return true;
        }
    }
}
